package com.quan.system.web.controller;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.validation.Valid;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.quan.common.bean.PageBean;
import com.quan.common.bean.ResultBean;
import com.quan.common.core.MyBaseController;
import com.quan.system.common.dto.DictDTO;
import com.quan.system.entity.SystemDict;
import com.quan.system.entity.SystemDictDetail;
import com.quan.system.service.SystemDictDetailService;
import com.quan.system.service.SystemDictService;

/**
 * <p>
 * 系统-字典 前端控制器
 * </p>
 *
 * @author 杨浩泉
 * @since 2019-06-14
 */
@RestController
@RequestMapping("/system/dict")
public class SystemDictController extends MyBaseController {
	
	@Autowired 
	private SystemDictService service;

	@Autowired 
    private SystemDictDetailService detailService;
    
    /**
	 * 添加
	 * 
	 * @param entity
	 * @param bindingResult
	 * @return
	 */
	@PostMapping("/add")
	public Object add(@Valid @RequestBody SystemDict entity, BindingResult bindingResult) {
		if (bindingResult.hasErrors()) {
			return ResultBean.warning(bindingResult.getFieldError().getRejectedValue().toString());
		}
		if(this.service.hasExist("code", entity.getCode(), SystemDict.class)) {
			return ResultBean.warning("该值已存在");
		}
		boolean save = this.service.save(entity);
		if (save) {
			return ResultBean.ok("提交成功");
		} else {
			return ResultBean.failure("提交失败");
		}
	}

	/**
	 * 根据ID删除
	 * 
	 * @param id
	 * @return
	 */
	@GetMapping("/deleteById/{id}")
	public Object deleteById(@PathVariable String id) {
		if (StringUtils.isNotBlank(id)) {
			boolean remove = this.service.removeById(id);
			if (remove) {
				return ResultBean.ok();
			} else {
				return ResultBean.failure("通过ID删除失败：[ " + id + " ]");
			}
		}
		return ResultBean.failure("请选项需要删除的记录");
	}

	/**
	 * 根据ID批量删除
	 * 
	 * @param params idList:["1","2"]
	 * @return
	 */
	@PostMapping("/deleteBatchIds")
	public Object deleteBatchIds(@RequestBody Map<String, Object> params) {
		if (null != params && !params.isEmpty()) {
			List<Long> idList = JSON.parseArray(params.get("idList").toString(), Long.class);
			boolean remove = this.service.removeByIds(idList);
			if (remove) {
				return ResultBean.ok();
			} else {
				return ResultBean.failure("通过ID删除失败：[ " + idList + " ]");
			}
		}
		return ResultBean.failure("请选项需要删除的记录");
	}

	/**
	 * 修改
	 * 
	 * @param entity
	 * @param bindingResult
	 * @return
	 */
	@PostMapping("/update")
	public Object update(@Valid @RequestBody SystemDict entity, BindingResult bindingResult) {
		if (bindingResult.hasErrors()) {
			return ResultBean.failure(bindingResult.getFieldError().getDefaultMessage().toString());
		}
		boolean update = this.service.updateById(entity);
		if (update) {
			return ResultBean.ok("修改成功");
		} else {
			return ResultBean.failure("修改失败");
		}
	}

	/**
	 * 根据ID查询
	 * 
	 * @param id
	 * @return
	 */
	@GetMapping("/get/{id}")
	public Object get(@PathVariable Long id) {
		SystemDict entity = this.service.getById(id);
		if (null != entity) {
			return ResultBean.ok(entity);
		} else {
			return ResultBean.failure("通过ID查询失败：[ " + id + " ]");
		}
	}

	/**
	 * 查询所有数据，不分页
	 * 
	 * @param entity
	 * @return
	 */
	@GetMapping(value = "/list")
	public Object list(SystemDict entity) {
		return ResultBean.ok(this.service.list(new QueryWrapper<SystemDict>(entity).orderByDesc("ctime")));
	}

	/**
	 * 分页查询数据
	 * 
	 * @param entity
	 * @return
	 */
	@GetMapping(value = "/page")
	public Object page(SystemDict entity) {
		return ResultBean.ok(this.service.selectPage(new QueryWrapper<SystemDict>(entity).orderByDesc("ctime"), new PageBean(request)));
	}
	
	
	/**
	 * 根据编码获取字典
	 * @param codes
	 * @return
	 */
	@PostMapping(value = "/getDictByCode")
	public Object getDictByCode(@RequestBody DictDTO dto) {
		
		Map<String, Object> map = new HashMap<String, Object>() ;
		
		if(null != dto.getCodes() && dto.getCodes().length > 0) {
			QueryWrapper<SystemDict> queryWrapper = new QueryWrapper<SystemDict>();
			queryWrapper.in("code", Arrays.asList(dto.getCodes())).select("id", "code", "status");
			List<SystemDict> list = this.service.list(queryWrapper);
			
			for (SystemDict dict : list) {
				QueryWrapper<SystemDictDetail> queryDictDetails = new QueryWrapper<SystemDictDetail>();
				queryDictDetails.eq("dict_id", dict.getId()).orderByDesc("sort").select("id", "label", "value", "selected", "status");
				List<SystemDictDetail> dictItems = this.detailService.list(queryDictDetails);
				
				map.put(dict.getCode(), dictItems);
			}
		}
		
		return ResultBean.ok(map);
	}


}



